import json
from datetime import datetime
from sqlalchemy.orm import session
from Model.default import get_db
from Model.mysocketio.info import Group_Room
from Model.user.User import user_expand


def update_userinfo_to_room(room_id,user_id,key,value,type,db:session=None,):
    """
    更新userinfo下对房间{}下的字段的信息
    :param room_id:
    :param user_id:
    :param key:
    :param value:
    :param time:
    :return:
    """
    if db is None:
        db=get_db()
        try:
            user_to_room = db.query(user_expand).filter_by(id=user_id).first()
            usertoroom = json.loads(user_to_room.room_info or json.dumps({}))
            usertoroom.setdefault(room_id,{})[key]=value
            usertoroom.setdefault(room_id,{})['type']=type
            # usertoroom['last_commit']=time
            user_to_room.room_info=json.dumps(usertoroom)
            db.commit()
            return  True
        except Exception as e:
            return False
    else:
        try:
            user_to_room = db.query(user_expand).filter_by(id=user_id).first()
            usertoroom = json.loads(user_to_room.room_info or json.dumps({}))
            usertoroom.setdefault(room_id,{})[key]=value
            # usertoroom['last_commit']=time
            user_to_room.room_info=json.dumps(usertoroom)
            # db.commit()
            # 如果是群组暂缓提交
            return  True
        except Exception as e:
            return False



def add_user_to_group(user_id, room_id):
    """
    更新房间的用户信息
    :param user_id:
    :param room_id:
    :return:
    """
    db = get_db()
    try:
        ROOM = db.query(Group_Room).filter_by(room_id=room_id).first()
        if not ROOM:
            return False
        user_info = json.loads(ROOM.user_info) if ROOM.user_info else {}
        for i in user_id:
            user_info.setdefault(i,{"joined_at": str(datetime.now()), "active": 1})
        ROOM.user_info = json.dumps(user_info)
        now = str(datetime.now())
        judge=update_userinfo_to_room(room_id,user_id,'joined_at', now,'group',db)
        if judge:
            db.commit()

    except Exception as e:
        db.rollback()
        pass
    finally:
        db.close()


def add_user_to_middle(user_id, group_id):
    db = get_db()
    pass


ADD_ROOM_USER_MAPPER = {
    # 临时会话，不限制人数数量
    'group': add_user_to_group,
}




